/**
 *创建日期：2018-7-17
 *作    者：YoungRemus
 *文 件 名：CookieUtil.java
 *描    述：TODO
 *版    本：V1.0
**/
package com.shenghua.utils;

import java.util.Iterator;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	private HttpServletRequest req;
	private HttpServletResponse res;
	
	public CookieUtil(){}
	
	public CookieUtil(HttpServletRequest req, HttpServletResponse res) {
		this.req = req;
		this.res = res;
	}
	
	public CookieUtil(HttpServletRequest req) {
		this.req = req;
	}

	public HttpServletRequest getReq() {
		return req;
	}

	public void setReq(HttpServletRequest req) {
		this.req = req;
	}

	public HttpServletResponse getRes() {
		return res;
	}

	public void setRes(HttpServletResponse res) {
		this.res = res;
	}
	
	public void addCookie(String name,String value){
		Cookie cookie =  new Cookie(name,value);
		cookie.setPath("/");//这个要跟删除Cookie时一样
		cookie.setMaxAge(7*24*60*60);
		res.addCookie(cookie);
	}

	public void addCookieByDay(String name,String value,int expiry){
		Cookie cookie =  new Cookie(name,value);
		cookie.setPath("/");//这个要跟删除Cookie时一样
		cookie.setMaxAge(expiry);
		res.addCookie(cookie);
	}
	
	public void delCookie(String name){
		Cookie cookie =  new Cookie(name,null);
		cookie.setPath("/");//这个要跟删除Cookie时一样
		cookie.setMaxAge(0);
		res.addCookie(cookie);
	}
	
	public void writeUser(java.util.HashMap<String,String> map){
		Set<String> set = map.keySet();
		Iterator<String> ite = set.iterator();
		while(ite.hasNext()){
			String key  = ite.next();
			String value = map.get(key);
			if(key!=null && !"".equals(key)){
				addCookie(key,value);
			}
		}
	}
	// 在浏览器未关闭之前 可以多次读取request中的cookie 
	// 关闭了浏览器 这个方法就无效了 需要用到js中的document.cookie
	public String readUser(String name,String psw){
		java.util.HashMap<String,String> map = new java.util.HashMap<String,String>();
		Cookie [] cookies = req.getCookies();
		/*for (Cookie cookie : cookies) {
			System.out.println(cookie.getName()+"/"+cookie.getValue());
		}*/
		for (int i = 0; i < cookies.length; i++) {
			//对cookies中的数据进行遍历
			cookies[i].setPath("/");	
			System.out.println(cookies[i].getName()+":"+cookies[i].getValue());
	        if (name.equals(cookies[i].getName())) {
	             map.put(name,cookies[i].getValue());
	        } else if(psw.equals(cookies[i].getName())){
	        	map.put(psw,cookies[i].getValue());	        	
	        }
		}
		if(!map.isEmpty()){
			return com.alibaba.fastjson.JSONObject.toJSONString(map);
		} else {
			return "";
		}
	}
}


